package com.yoomiito.app.ui.list

import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.appbar.AppBarLayout
import com.gyf.barlibrary.ImmersionBar
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.adapter.goods.list.sort.StarStoreGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeBaoPinGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeYouPinGoodsAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.gift.GiftGoods
import com.yoomiito.app.model.gift.GiftGoodsList
import com.yoomiito.app.model.gift.GiftType
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity
import com.yoomiito.app.ui.order.sureorder.shopcar.ShopCarActivity
import com.yoomiito.app.ui.search.youpin.YouPinSearchActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.act_goods_sort.*
import kotlinx.android.synthetic.main.act_youpin_goods.frameLayout
import kotlinx.android.synthetic.main.fm_rcy.*
import kotlinx.android.synthetic.main.icon_shop_car.*
import kotlin.math.abs

/**
 * 优品专区
 * 爆品专区
 * 淘宝专区
 * 带顶部主图的列表
 */
class GoodsSortList_1Activity : BaseActivity<GoodsSortList_1Presenter>() {

    private var mGoodsType: Int = AllCode.YouPin//初始化
    private lateinit var mAdapter: BaseQuickAdapter<GiftGoods, BaseViewHolder>
    private var mCurrentPage: Int = 1
    private var mSort: Int = 0//排序
    private var mType: Long = 3 //商品类型
    private var mGoodsTypeToData: Int = 3
    private var salesSort: Int = 0//排序
    private var categorizeId : Int = 0//


    public override fun initImmersionBar() {
        ImmersionBar.with(this).keyboardEnable(false).init()
    }

    override fun getLayoutId(): Int = R.layout.act_goods_sort_1

    override fun newP(): GoodsSortList_1Presenter = GoodsSortList_1Presenter(App.mAppConfig)

    companion object {
        fun start(context: Context, title: String, type: Int) {
            val intent = Intent(context, GoodsSortList_1Activity::class.java)
            intent.putExtra(Constant.DATA, title)
            intent.putExtra(Constant.TYPE, type)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        mGoodsType = intent.getIntExtra(Constant.TYPE, AllCode.YouPin)
        titleTv.text = intent.getStringExtra(Constant.DATA)
        back.setOnClickListener { finish() }
        mGoodsTypeToData = when (mGoodsType) {
            AllCode.BaoPin -> 2
            AllCode.YouPin -> 3
            AllCode.AgentMall -> 4
            AllCode.StarStore -> 5//星店
            else -> {
                YMToast.showText("数据异常")
                finish()
                0
            }
        }
        when (mGoodsType) {
            AllCode.BaoPin -> {
                shopCarLl.visibility = View.VISIBLE
                shopCar.visibility = View.VISIBLE
                actBgAct.setImageResource(R.drawable.baopin_bg)
                shopCarLl.setOnClickListener {
                    if (App.mAppConfig.isLogin) {
                        ShopCarActivity.start(this)
                    } else {
//                        AllUtils.toLogin(this, AllCode.LoginIn)
                        AllUtils.toLogin(this@GoodsSortList_1Activity, AllCode.LoginIn)

                    }
                }
            }
            AllCode.YouPin -> {
                actBgAct.setImageResource(R.drawable.youpin_bg)
                shopCar.visibility = View.GONE
                shopCarLl.visibility = View.VISIBLE
                searchIv.visibility = View.VISIBLE
                searchIv.setOnClickListener { YouPinSearchActivity.start(this) }
            }
        }
        initAppbarLayout()
        initTabView()
        initStatusView()
        initRefresh()
        initRcy()
        showNewFlag(false)
        showLoading()
        p.getGoodsType(mGoodsTypeToData)
        requestData()
    }

    private fun initAppbarLayout() {
        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, i ->
            when {
                i == 0 -> {//展开
                    toolbarLl.setBackgroundResource(R.color.color_tran)
                    titleTv.visibility = View.INVISIBLE
                    val d = show_new.background as GradientDrawable
                    d.setColor(ResUtil.getColor(R.color.color_FF035B))
                }
                abs(i) >= appBarLayout.totalScrollRange -> {//折叠
                    toolbarLl.background = ColorUtils.gradient("#FFFF246C", "#FFFF035B")
                    titleTv.visibility = View.VISIBLE
                    val d = show_new.background as GradientDrawable
                    d.setColor(ResUtil.getColor(R.color.color_tran))
                }
                else -> {//中间
                    toolbarLl.setBackgroundResource(R.color.color_tran)
                    titleTv.visibility = View.INVISIBLE
//                    if (abs(i)>=appBarLayout.totalScrollRange/2){
//                        appBarLayout.setExpanded(false,true)
//                    }else{
//                        appBarLayout.setExpanded(true,true)
//                    }
                }
            }
        })
    }

    /**
     *
     */
    private fun requestData() {
//        p.getGoodsList(mSort, mCurrentPage, mType, mGoodsTypeToData)
        p.getGoodsList(mSort, mCurrentPage, mType, categorizeId, salesSort)

    }

    override fun onStart() {
        super.onStart()
        if (mGoodsType == AllCode.BaoPin && App.mAppConfig.isLogin) {
            p.getList(1)
        }
    }

    private fun initTabView() {
        tabView.setDownName("_des")
                .setUpName("_asc")
                .setPriceFirstName("sale_price")
                .setSaleFirstName("volume")
                .showSort()
                .setDefault()

        tabView.setOnChangeListener { sort,salesSort, _ ->
            mSort = sort
            this.salesSort = salesSort
            mCurrentPage = 1
            requestData()
        }

        tabView.setOnSortClickListener { giftType ->
            mCurrentPage = 1
            categorizeId = giftType.id.toInt()
            showLoading()
            requestData()
        }

    }

    private fun initStatusView() {
        mStatusManager = StatusManager.Builder(this)
                .addType(ContentType(R.layout.fm_rcy))
                .addType(EmptyType().setEmptyContent("暂无商品"))
                .build()
        frameLayout.addView(mStatusManager.view())
    }

    private fun initRefresh() {
        fm_refreshLayout.setOnRefreshListener {
            mCurrentPage = 1
            requestData()
        }

        fm_refreshLayout.setOnLoadMoreListener {
            mCurrentPage++
            requestData()
        }
    }

    private fun initRcy() {
        fm_rcy.setBackgroundResource(R.color.color_F4F4F4)
        fm_rcy.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        val sd = SpacingDecoration(DensityUtil.dp2px(10f), DensityUtil.dp2px(10f), true)
        fm_rcy.addItemDecoration(sd)

        when (mGoodsType) {
            AllCode.YouPin -> {
                mAdapter = ThemeYouPinGoodsAdapter(null)//优品
            }
            AllCode.BaoPin -> {
                mAdapter = ThemeBaoPinGoodsAdapter(null)
//                val view = LayoutInflater.from(this).inflate(R.layout.icon_shop_car, null)
//                view.setOnClickListener {
//                    if (App.mAppConfig.isLogin) {
//                        ShopCarActivity.start(this)
//                    } else {
//                        AllUtils.toLogin(this, AllCode.LoginIn)
//                    }
//                }
//                val lp = FrameLayout.LayoutParams(DensityUtil.dp2px(48f), DensityUtil.dp2px(48f))
//                lp.bottomMargin = DensityUtil.dp2px(12f)
//                lp.rightMargin = DensityUtil.dp2px(12f)
//                lp.gravity = Gravity.RIGHT or Gravity.BOTTOM
//                frameLayout.addView(view, lp)
            }//爆品
            AllCode.AgentMall -> mAdapter = ThemeYouPinGoodsAdapter(null)//区代商城
            AllCode.StarStore -> {
                fm_rcy.removeItemDecoration(sd)
                fm_rcy.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(12f), DensityUtil.dp2px(10f), true))
                mAdapter = StarStoreGoodsAdapter(null)

            }//星店商城
        }
        fm_rcy.adapter = mAdapter
        mAdapter?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            var info = mAdapter.data[position]
            NewGoodsInfoActivity.toGoodsInfo(this@GoodsSortList_1Activity, info.id.toString(), "2")
        }
    }

    fun showGift(goodsList: GiftGoodsList) {
        val data = goodsList.data
        if (mCurrentPage == 1) {
            if (data == null || data.size == 0) {
                mStatusManager.showEmpty()
            } else {
                mStatusManager.showContent()
                mAdapter.setNewData(data)
            }
            fm_refreshLayout.finishRefresh(true)
            fm_refreshLayout.setNoMoreData(false)
        } else {
            fm_refreshLayout.finishLoadMore(true)
            if (data == null || data.size == 0) {
                Toast.makeText(context, "没有更多了", Toast.LENGTH_SHORT).show()
                fm_refreshLayout.finishLoadMoreWithNoMoreData()
            } else {
                mAdapter.addData(data)
            }
        }
    }

    fun setType(types: MutableList<GiftType>?) {
        if (types != null) {
            types.add(0, GiftType(0, "全部", true))
            tabView.setGiftTypes(types)
        }
    }

    fun showNewFlag(show: Boolean) {
        show_new.visibility = if (show) View.VISIBLE else View.GONE
    }

    override fun eventMessage(eventMessage: EventMessage?) {
        super.eventMessage(eventMessage)
        if (Type.EventMsgType.LoginSuccess==eventMessage?.eventType || Type.EventMsgType.LoginOut==eventMessage?.eventType){
            mCurrentPage = 1
            requestData()
        }
    }
}